package com.lhgray.sglhome.presentation.ui.compose

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.lhgray.sglhome.domain.model.ListItemOperation
import com.lhgray.sglhome.domain.model.ListItemStatus
import com.lhgray.sglhome.domain.model.ListItemText
import com.lhgray.sglhome.domain.model.WarehouseBean
import com.lhgray.sglhome.domain.model.UserData
import com.lhgray.sglhome.presentation.viewModel.HomeViewModel
import com.lhgray.sglhome.presentation.viewModel.WarehouseViewModel


/**
 * 仓储的页面
 */
@Composable
fun WarehousePage(
    homeViewModel: HomeViewModel,
    onScanBarcode: () -> Unit,//跳转到扫一扫的页面的
    viewModel: WarehouseViewModel = hiltViewModel()
) {
    val fileNo by homeViewModel.fileNo.collectAsState()
    val userData by homeViewModel.userData.collectAsStateWithLifecycle()
    val warehouseState by viewModel.uiState.collectAsStateWithLifecycle()
    LaunchedEffect(fileNo) {
        if (fileNo.isNotEmpty()) {
            println("fileNo更新了WarehousePage$fileNo")
            viewModel.getWarehouseJob(fileNo)
        }
    }
    homeViewModel.uploadLoadingOrError(warehouseState.isLoading,warehouseState.errorMsg ?: "",warehouseState.toast)
    Column(Modifier.background(color = Color.White).fillMaxSize()) {
        WarehouseComposeHander(
            userData,
            onScanBarcode,
            {
                homeViewModel.upFileNo(it)
                viewModel.getWarehouseJob(it)
            },
            fileNo
        )
        val warehouseBean = warehouseState.warehouseBean
        if (warehouseBean != null && warehouseState.warehouseBean?.list_item_label?.isNotEmpty() == true) {
            WarehouseCompose(
                viewModel,
                warehouseBean
            ) {
                viewModel.postWarehouseJob(it.copy(source = warehouseBean.source))
            }
        }
    }


}

@Composable
fun WarehouseComposeHander(
    userData: UserData,
    onScanBarcode: () -> Unit,//跳转到扫码
    onSearchNumber: (String) -> Unit,//输入框的数据进行搜索的
    inputTextFieldValue: String,
) {
    UserHandleView(userData)
    InputSearch(inputTextFieldValue, onScanBarcode, onSearchNumber)
}

@Composable
fun WarehouseCompose(
    warehouseViewModel: WarehouseViewModel,
    warehouseBean: WarehouseBean,
    onClick: (WarehouseBean) -> Unit,
) {
// 使用 var + mutableState 管理本地状态
    var warehouseBeanState by remember { mutableStateOf(warehouseBean) }

    // 监听外部传入的 warehouseBean 变化，强制更新本地状态
    LaunchedEffect(warehouseBean) {
        warehouseBeanState = warehouseBean
    }

    //列表的数据
    LazyColumn(
        modifier = Modifier
            .fillMaxWidth()
            .padding(10.dp, 10.dp)


    ) {
        itemsIndexed(warehouseBeanState.list_item_label) { _, item ->
            LazyColumnItemOrder(item)
        }
        itemsIndexed(warehouseBeanState.list_item_text) { index, item ->
            FormInputSection(item) {

                val newList = warehouseBeanState.list_item_text.toMutableList().apply {
                    set(index, item.copy(item_text = it))
                }
                warehouseBeanState = warehouseBeanState.copy(list_item_text = newList)
                warehouseViewModel.uploadwarehouseBean(warehouseBean.copy(list_item_text = newList))
            }
        }
        itemsIndexed(warehouseBeanState.list_item_operation) { index, item ->
            CheckboxRow(item, {
                val newList = warehouseBeanState.list_item_operation.toMutableList().apply {
                    set(index, item.copy(qty = it.toIntOrNull() ?: 0))
                }
                warehouseBeanState = warehouseBeanState.copy(list_item_operation = newList)
                warehouseViewModel.uploadwarehouseBean(warehouseBean.copy(list_item_operation = newList))

            }, {
                val newList = warehouseBeanState.list_item_operation.toMutableList().apply {
                    set(index, item.copy(check_flag = if (it) 1 else 0))
                }
                warehouseBeanState = warehouseBeanState.copy(list_item_operation = newList)
                warehouseViewModel.uploadwarehouseBean(warehouseBean.copy(list_item_operation = newList))
            })
        }
        item {
            HorizontalDivider(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(0.3.dp),
                color = Color.Black.copy(alpha = 0.5f)
            )
        }

        itemsIndexed(warehouseBeanState.list_item_status) { index, item ->
            SingleCheckboxRow(item) {
                val newList = warehouseBeanState.list_item_status.toMutableList().apply {
                    set(index, item.copy(check_flag = if (it) 1 else 0 ))
                }
                warehouseBeanState = warehouseBeanState.copy(list_item_status = newList)
                warehouseViewModel.uploadwarehouseBean(warehouseBean.copy(list_item_status = newList))

            }

        }
        item {
            SubmitButton {
                onClick(
                    WarehouseBean(
                        list_item_label = warehouseBeanState.list_item_label,                   //  listItemOperationChange[index] = item.copy(qty = it.toIntOrNull() ?: 0) ,
                        list_item_text = warehouseBeanState.list_item_text,
                        list_item_operation = warehouseBeanState.list_item_operation,
                        list_item_status = warehouseBeanState.list_item_status,
                    )
                )
            }
        }

    }


}

@Composable
fun FormInputSection(
    listItemText: ListItemText,
    locationInputChange: (String) -> Unit
) {
    var locationInput by remember { mutableStateOf(listItemText.item_text) }
    LaunchedEffect(listItemText) {
        locationInput = listItemText.item_text
    }
    Column(Modifier.padding(0.dp, 10.dp, 10.dp, 0.dp)) {
        // 仓库位置
        Row {
            Text(
                text = listItemText.show_title,
                modifier = Modifier
                    .fillMaxWidth(0.3f)
                    .align(alignment = Alignment.CenterVertically)
            )
            TextField(
                value = locationInput,
                onValueChange = {
                    locationInput = it
                    locationInputChange(it)
                },
                modifier = Modifier.weight(1.0f),
                placeholder = {
                    Text(
                        text = listItemText.show_title,
                        color = Color.Black,
                    )
                }
            )
        }
    }
}

@Composable
fun CheckboxRow(
    listItemOperation: ListItemOperation,
    inputTextChange: (String) -> Unit,
    checkBoxChange: (Boolean) -> Unit
) {
    var inputText by remember { mutableStateOf(TextFieldValue(listItemOperation.qty.toString())) }
    var isBoxChecked by remember { mutableStateOf(listItemOperation.check_flag == 1) }

    LaunchedEffect(listItemOperation) {
        inputText = TextFieldValue(listItemOperation.qty.toString())
        isBoxChecked = listItemOperation.check_flag == 1
    }
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.padding(vertical = 6.dp)
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth(0.4f)
        ) {
            Checkbox(
                modifier = Modifier
                    .padding(0.dp)
                    .width(25.dp),
                checked = isBoxChecked,
                onCheckedChange = {
                    isBoxChecked = !isBoxChecked
                    checkBoxChange(isBoxChecked)
                })
            Spacer(modifier = Modifier.width(1.dp))
            Text(text = listItemOperation.show_title ?: "")

        }
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(text = "Qty")
            TextField(
                value = inputText,
                onValueChange = {
                    inputText = it
                    inputTextChange(it.text)
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 8.dp),
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                singleLine = true,
                placeholder = {
                    Text(
                        text = "Qty",
                        color = Color.Black,
                    )
                }
            )
        }
    }
}


@Composable
fun SingleCheckboxRow(
    item: ListItemStatus,
    boxCheckedChange: (Boolean) -> Unit
) {
    var isBoxChecked by remember { mutableStateOf(item.check_flag == 1) }
    LaunchedEffect(item) {
        isBoxChecked = item.check_flag == 1
    }
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.padding(vertical = 4.dp)
    ) {
        Checkbox(
            modifier = Modifier
                .padding(0.dp)
                .width(25.dp),
            checked = isBoxChecked,
            onCheckedChange = {
                isBoxChecked = !isBoxChecked
                boxCheckedChange(isBoxChecked)
            }
        )
        Spacer(modifier = Modifier.width(1.dp))
        Text(text = item.show_title ?: "")
    }
}

@Composable
fun SubmitButton(onClick: () -> Unit) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(10.dp)
    ) {
        Button(
            onClick = onClick,
            modifier = Modifier
                .align(Alignment.CenterEnd)
                .fillMaxWidth(0.4f)
                .padding(top = 5.dp),
            shape = RoundedCornerShape(8.dp),
            colors = ButtonDefaults.buttonColors(Color(0xFF1A73E8))
        ) {
            Text("Submit", color = Color.White)
        }

    }
}

